// src/stores/articleEdit.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {createArticle, getArticleEdit} from '@/api/article'
import { ElMessage } from 'element-plus'

export const useArticleEditStore = defineStore('articleEdit', () => {
    // 表单数据
    const articleForm = ref({
        id: '',
        title: '',
        summary: '',
        contentHtml: '',
        category: '',
        tags: [],
        thumbnailUrl: '',
        mainImageUrl: '',
        status: 0,
        isTop: false,
        isHot: false,
        isRecommend: false
    })

    const loading = ref(false)

    // 获取文章
    async function fetchArticleEdit(id) {
        loading.value = true
        try {
            const res = await getArticleEdit(id)
            articleForm.value = res.data
        } catch (error) {
            ElMessage.error('获取文章失败')
        } finally {
            loading.value = false
        }
    }

    // 保存文章
    async function save(isDraft = true) {
        loading.value = true
        try {
            articleForm.value.status = isDraft ? 0 : 1
            const res = await createArticle(articleForm.value)
            ElMessage.success(isDraft ? '保存草稿成功' : '发布成功')
            return res
        } catch (error) {
            ElMessage.error(isDraft ? '保存草稿失败' : '发布失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 重置表单
    function resetForm() {
        articleForm.value = {
            id: '',
            title: '',
            summary: '',
            contentHtml: '',
            category: '',
            tags: [],
            thumbnailUrl: '',
            mainImageUrl: '',
            status: 0,
            isTop: false,
            isHot: false,
            isRecommend: false
        }
    }

    return {
        articleForm,
        loading,
        fetchArticleEdit,
        save,
        resetForm
    }
})